<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors',1);
$expected=array(
	  'cmd'
	, 'api'
	, 'projectId'
	, 'stages'
	, 'sort'
	, 'dir'
	, 'start'
	, 'limit'
);

// Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? ${"_$_SERVER[REQUEST_METHOD]"}[$formvar]:NULL;

include_once('../../../config.php');
include_once($config['paths']['base'] . 'resources/api/classes/class.classify.php');

$classify = new Classify();

$valid = true;
header('Content-type: application/json');
switch($cmd) {
	case 'listProjects':
		$timeStart = microtime(true);
		$stages = json_decode(stripslashes(trim($stages)),true);
		if(is_array($stages) && count($stages)) {
			$filter['filter'][] = array('data' => array('type' => 'list', 'value' => @implode(',',$stages)),'field' => 'stage');
		}
		if($projectId != '') {
			$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => $projectId),'field' => 'projectId');
		}
		if(in_array($sort, array('projectId','stage','dateAdded','ip','url'))) {
			$filter['order'] = array(array('field' => $sort, 'dir' => $dir));
		}
		$filter['start'] = ($start == '') ? 0 : $start;
		$filter['limit'] = ($limit == '') ? 25 : $limit;
		$projects = $classify->project->getByFilter($filter);
		$projects = is_null($projects) ? array() : $projects;
		print json_encode(array('success' => true, 'recordCount' => $classify->project->get('recordCount'),'processTime' => (microtime(true) - $timeStart), 'records' => $projects));
		break;
	case 'deleteProject':
		if(!$classify->project->loadByProjectId($projectId)){
			$valid = false;$code = 104;
		}
		if($valid) {
			$path = $config['paths']['project'] . $projectId . '/';
			if(file_exists($path)) {
				recursiveDelete($path);
			}
			$classify->project->deleteProject($projectId);
			print json_encode(array('success' => true));
		} else {
			print json_encode(array('success' => false, 'error' => array('code' => $code, 'msg' => $classify->getError($code))));
		}
		break;
	default:
		print json_encode(array('success' => false, 'error' => array('code' => '', 'msg' => 'No Command Given.')));
		break;
}
?>